import styles from './id.less';
import { useState, useEffect } from 'react';
import { history, Link, useIntl, useParams, useLocation } from 'umi';
import AreaCode from '@/data/areaCode';
import {
  Button,
  Table,
  Radio,
  Divider,
  Space,
  Drawer,
  Form,
  Select,
  Input,
  Switch,
  Row,
  Col,
  message,
  Popconfirm,
  Modal,
  Tag,
} from 'antd';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;

import request from '@/utils/request';
import NoDataExplain from './components/idExplain';

import { leadStagefn, leadSourcefn, priorityfn } from '@/data/options';

const RosterUserPage = function () {
  const intl = useIntl();
  const [form] = Form.useForm();
  const params = useParams();

  const leadStage = leadStagefn();
  const leadSource = leadSourcefn();
  const priority = priorityfn();

  const columns = [
    {
      title: intl.formatMessage({ id: 'name' }),
      width: 150,
      dataIndex: 'name',
      fixed: 'left',
      render: (text: string, record: any) => (
        <Link to={`/profile/${record.chatId}`}>
          {text || `${record.areaCode}${record.phone}`}
        </Link>
      ),
    },
    {
      title: intl.formatMessage({ id: 'label' }),
      width: 150,
      dataIndex: 'label',
      render: (text: string, record: any) => (
        <>
          {record.tagList && record.tagList.length
            ? record.tagList &&
              record.tagList.map((n) => <Tag color={n.color}>{n.tagName}</Tag>)
            : null}
        </>
      ),
    },
    {
      title: intl.formatMessage({ id: 'email' }),
      width: 150,
      dataIndex: 'email',
    },
    {
      title: intl.formatMessage({ id: 'phonenumber' }),
      width: 150,
      dataIndex: 'phone',
    },
    {
      title: intl.formatMessage({ id: 'companyname' }),
      width: 150,
      dataIndex: 'companyName',
    },
    {
      title: intl.formatMessage({ id: 'jobtitle' }),
      width: 150,
      dataIndex: 'jobTitle',
    },
    {
      title: intl.formatMessage({ id: 'contactowner' }),
      width: 150,
      dataIndex: 'contactOwner',
    },
    {
      title: intl.formatMessage({ id: 'leadstage' }),
      width: 150,
      dataIndex: 'leadstage',
      render: (text: string, record: any) => (
        <div>{leadStage.find((n) => n.value === record.leadStage)?.label}</div>
      ),
    },
    {
      title: intl.formatMessage({ id: 'leadsource' }),
      width: 150,
      dataIndex: 'leadsource',
      render: (text: string, record: any) => (
        <div>
          {leadSource.find((n) => n.value === record.leadSource)?.label}
        </div>
      ),
    },
    {
      title: intl.formatMessage({ id: 'priority' }),
      width: 150,
      dataIndex: 'priority',
      render: (text: string, record: any) => (
        <div>{priority.find((n) => n.value === record.priority)?.label}</div>
      ),
    },
    // {
    //   title: intl.formatMessage({ id: 'country' }),
    //   width: 150,
    //   dataIndex: 'country',
    // },

    {
      title: intl.formatMessage({ id: 'subscriber' }),
      width: 150,
      dataIndex: 'subscriber',
      render: (text: string) => (
        <div>
          {text === 'Y'
            ? intl.formatMessage({ id: 'yes' })
            : intl.formatMessage({ id: 'no' })}
        </div>
      ),
    },
    {
      title: intl.formatMessage({ id: 'lastcontactfromyou' }),
      width: 150,
      dataIndex: 'lastContactFromYou',
    },
    {
      title: intl.formatMessage({ id: 'lastcontactfromcustomers' }),
      width: 180,
      dataIndex: 'lastContactFromCustomers',
    },
    {
      title: intl.formatMessage({ id: 'created' }),
      width: 150,
      dataIndex: 'createdDate',
    },
    {
      title: intl.formatMessage({ id: 'lastupdate' }),
      width: 150,
      dataIndex: 'updatedDate',
    },
    // {
    //   title: intl.formatMessage({ id: 'action' }),
    //   width: 100,
    //   dataIndex: 'action',
    //   fixed: 'right',
    //   render: (text: string, record: any) => (
    //     <div style={{ display: 'flex' }}>
    //       {/* <Button type="link" onClick={() => openEditContact(record)}>
    //         编辑
    //       </Button> */}
    //       <Popconfirm
    //         placement="bottomRight"
    //         title="确定移出该联系人?"
    //         onConfirm={() => onRemove(record)}
    //         okText={intl.formatMessage({ id: 'yes' })}
    //         cancelText={intl.formatMessage({ id: 'no' })}
    //       >
    //         <Button type="link">{intl.formatMessage({ id: 'remove' })}</Button>
    //       </Popconfirm>
    //     </div>
    //   ),
    // },
  ];
  const [totalPeople, setTotalPeople] = useState(0);
  const [rosterName, setRosterName] = useState();
  const [createVisible, setCreateVisible] = useState(false);
  const [joinRosterVisible, setJoinRosterVisible] = useState(false);
  const [contactList, setContactList] = useState([]);
  const [rosterList, setRosterList] = useState([]);
  const [rowSelected, setRowSelected] = useState([]);
  const [newRostername, setNewRostername] = useState('');
  const [rosterSelected, setRosterSelected] = useState({});

  // rowSelection object indicates the need for row selection
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows,
      );
      setRowSelected(selectedRows);
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };
  const onOpen = () => {
    setCreateVisible(true);
  };
  const onClose = () => {
    setCreateVisible(false);
    form.resetFields();
  };

  useEffect(() => {
    getListRoster();
  }, [params.id]);

  const getListRoster = () => {
    request.get(`/roster/${params.id}`).then((res) => {
      const { contactList = [], rosterName, totalPeople } = res.data.roster;
      setRosterName(rosterName);
      setContactList(contactList);
      setTotalPeople(totalPeople);
    });
  };

  const onCreateUser = () => {
    form.submit();
  };
  const onSubmitCreateUser = (values: any) => {
    const data = { ...values };
    data.subscriber = data.subscriber === false ? 'N' : 'Y';
    request.post('/contact/create', data).then((res) => {
      message.success(intl.formatMessage({ id: 'createsuccess' }));
      onClose();
      form.resetFields();
    });
  };

  const onRemoveRoster = () => {
    confirm({
      title: intl.formatMessage({ id: 'RU_deleteroster' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'RU_deleteroster_ex' }),
      onOk() {
        request.delete(`/roster/${params.id}`).then((res) => {
          history.replace('/roster');
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const onRemoveUser = () => {
    const data = rowSelected.map((n) => {
      return {
        contactId: n.id,
        rosterId: params.id,
      };
    });
    request.post(`/rosterUser/del`, data).then((res) => {
      message.success(intl.formatMessage({ id: 'removesuccess' }));
      getListRoster();
      setRowSelected([]);
    });
  };

  // const onRemove = (record: any) => {
  //   request.delete(`/rosterUser/${record.id}`).then((res) => {
  //     message.success('移出成功');
  //   });
  // };

  const openEditContact = (record: any) => {
    form.setFieldsValue(record);
    onOpen();
  };

  const onOpenJoinRoster = () => {
    setJoinRosterVisible(true);
  };
  const onCloseJoinRoster = () => {
    setJoinRosterVisible(false);
  };
  const onSubmitJoinRoster = () => {
    if (rosterName || rowSelected.length) {
      const contactId = rowSelected.map((n: any) => n.id);
      console.log('contactId', contactId, rosterSelected);
      const data: any = {
        contactId, //联系人id :contact.id
      };
      if (rosterSelected.id) {
        data.rosterId = rosterSelected.id;
      } else {
        data.rosterName = rosterSelected.rosterName;
      }
      request.post('/rosterUser/create', data).then((res) => {
        message.success(intl.formatMessage({ id: 'addsuccess' }));
        onCloseJoinRoster();
      });
    }
  };

  const onNameChange = (e: any) => {
    const { value } = e.target;
    setNewRostername(value);
  };

  const addItem = () => {
    if (newRostername) {
      setRosterList([...rosterList, { rosterName: newRostername }]);
      setNewRostername('');
    }
  };

  const onSelectRoster = (value: any, e: any) => {
    console.log(value, e, rosterList);
    setRosterSelected(rosterList[e.key]);
  };

  const onChangeRoster = (e: any) => {
    const { value } = e.target;
    setRosterName(value);
  };

  const onSaveRosterName = () => {
    request
      .patch('/roster/edit', {
        id: params.id,
        rosterName,
      })
      .then((res) => {
        message.success(intl.formatMessage({ id: 'savesuccess' }));
      });
  };
  return (
    <div className={styles.rosterContainer}>
      <div className={styles.left}>
        <div style={{ marginBottom: 20 }}>
          <Link to="/roster">
            <Button>{intl.formatMessage({ id: 'goBackRoster' })}</Button>
          </Link>
        </div>
        <div className={styles.title}>
          {intl.formatMessage({ id: 'roster' })}
        </div>
        <div className={styles.subtitle}>
          {totalPeople} {intl.formatMessage({ id: 'contacts_s' })}
        </div>
        <div className={styles.subtitle}>
          {intl.formatMessage({ id: 'name' })}
          <div>
            <Input value={rosterName} onChange={onChangeRoster}></Input>
          </div>
        </div>
        <Space>
          <Button type="primary" onClick={onSaveRosterName}>
            {intl.formatMessage({ id: 'save' })}
          </Button>
          <Button onClick={onRemoveRoster}>
            {intl.formatMessage({ id: 'removeRoster' })}
          </Button>
        </Space>
      </div>
      <div className={styles.right}>
        <div className={styles.ccHead}>
          <div className={styles.ccHeadTitle}>
            {/* <Input
              placeholder={intl.formatMessage({ id: 'search' })}
              style={{ width: 400, marginRight: 10 }}
            ></Input>
            <Button>{intl.formatMessage({ id: 'search' })}</Button> */}
          </div>
          <Space>
            {/* <Button type="primary" onClick={onOpen}>编辑资料栏</Button> */}
            <Button
              onClick={() => history.push(`/contacts?rosterId=${params.id}`)}
            >
              {intl.formatMessage({ id: 'addToRoster' })}
            </Button>
            <Button
              type="primary"
              disabled={rowSelected.length === 0}
              onClick={onRemoveUser}
            >
              移出
            </Button>
            {/* <Button onClick={onOpen}>
              {intl.formatMessage({ id: 'import' })}
            </Button>
            <Button type="primary" onClick={onOpen}>
              {intl.formatMessage({ id: 'create' })}
            </Button> */}
          </Space>
        </div>
        <div className={styles.ccTable}>
          <div className={styles.tablemain}>
            <Table
              className={`${styles.liaisonTable}, nodatanoshow`}
              rowKey="id"
              rowSelection={{
                type: 'checkbox',
                ...rowSelection,
              }}
              scroll={{ x: '100%' }}
              columns={columns}
              dataSource={contactList}
              pagination={false}
            />
            {!contactList.length ? (
              <div className={styles.nodatacon}>
                <NoDataExplain
                  oncreate={() =>
                    history.push(`/contacts?rosterId=${params.id}`)
                  }
                />
              </div>
            ) : (
              ''
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default RosterUserPage;
